package com.toocms.jinjuhang.dialog.dedicated_service

import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import com.blankj.utilcode.util.StringUtils
import com.toocms.jinjuhang.R

class DedicatedServiceDialog : DialogFragment() {
    private var phoneCodeTv: TextView? = null
    var phoneCode: String = ""
        set(value) {
            field = value
            phoneCodeTv?.text = "拨打电话：${value}"
        }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.dialog_dedicated_service, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.apply {
            findViewById<TextView>(R.id.title_tv).text =
                "${StringUtils.getString(R.string.app_name)}福利"
            phoneCodeTv = findViewById(R.id.phone_code_tv)
            phoneCodeTv?.text = "拨打电话：${phoneCode}"
            findViewById<Button>(R.id.dial_btn).setOnClickListener {
                dismiss()
                if (phoneCode.isNullOrEmpty()) return@setOnClickListener
                val intent = Intent(Intent.ACTION_DIAL)
                intent.data = Uri.parse("tel:${phoneCode}")
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivity(intent)
            }
        }

    }

    override fun onStart() {
        super.onStart()
        config()
    }

    private fun config() {
        dialog?.run {
            setCancelable(true)
            setCanceledOnTouchOutside(true)
            window
        }?.apply {
            setLayout(
                (displayMetrics().widthPixels * 0.75f).toInt(),
                WindowManager.LayoutParams.WRAP_CONTENT
            )
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        }
    }


    private fun displayMetrics() = resources.displayMetrics

}